#!/bin/sh
#--------------------------------------------------------------
#   FileName  :   ReadNetConfig.sh
#   Author    :   ghzhangz
#   Descriptor:   Shell 读取网络配置
#--------------------------------------------------------------

function removeAutoFlagForSpecifiedNicName()
{
    local specifiedNicName=$1
    local autoNicFileFlag="${isAutoFlagPath_Prefix}${specifiedNicName}"
    if  test -e $autoNicFileFlag ; then
        local rmCommand="rm -f $autoNicFileFlag"
        exec $rmCommand | true
    fi
}

function autoObtainIpForSpecifiedNicName()
{
    local specifiedNicName=$1
    dhcp_client_service stop  $specifiedNicName
    dhcp_client_service start $specifiedNicName
}

function setToDefaultStaticIpForSpecifiedNicName()
{
    local specifiedNicName=$1
    for index in ${!defaultNetConfig[@]}
    do
        local defaultCommand=${defaultNetConfig[$index]}
        local defaultCommandByNicName=`echo $defaultCommand | grep $specifiedNicName`
        if [ -n "$defaultCommandByNicName" ]; then
            exec $defaultCommand | true
            if [ $debug == true ]; then
                echo -e "::$LINENO)\033[33m The current status is the default static IP address of NIC[$nicName] \033[0m"
            fi
        fi
    done
}

function readCacheConfig()
{
    fileName=$1
    sectionName=$2
    keyName=$3
    if test -e ${fileName}; then
        keyValue=$(cat $fileName | ${awkPath} '/\['$sectionName'\]/{f=1;next} /\[*\]/{f=0} f' | grep $keyName | ${awkPath} -v FS='=' '{print $2}')
        echo $keyValue
    else
        echo "file does not exists"
        return 1
    fi
}

function setDefaultRoute()
{
    local gateway=`readCacheConfig $cacheFilePath eth0 gateway`
    local setGatewayCommand=""
    if [ -n "$gateway" ]; then
        setGatewayCommand="$routePath add default gw $gateway"
    fi
    if [ -n "$setGatewayCommand" ]; then
        echo "setGatewayCommand = $setGatewayCommand"
        exec $setGatewayCommand | true
    fi
    routeList=(`$routePath -n | grep UG | ${awkPath} '{print $2}'`)
    for item in ${routeList[@]}; do
        if [ "$item" != "$gateway" ]; then
            $routePath del default gw $item
        fi
    done;
}

function setIpconfigByNicName()
{
    item=$1
    if [ $nocheck == false ]; then
        nicNameValid=false
        for nicName in ${NIC_NameArray[@]}
        do
            if [ '['"$nicName"']' == "$item" ]; then
                if [ $debug == true ]; then
                    echo -e "::$LINENO)\033[33m  Nic $nicName is valid and will be set \033[0m"
                fi
                nicNameValid=true
            fi
        done
        if [ $nicNameValid == false ]; then
            echo -e "::$LINENO)\033[33m  Nic $nicName is invalid \033[0m"
            return
        fi
    fi
    deviceName=`echo $item | sed 's/[][]//g'`
    local ip=`readCacheConfig $cacheFilePath $deviceName ip`
    local netmask=`readCacheConfig $cacheFilePath $deviceName netmask`
    local broadcast=`readCacheConfig $cacheFilePath $deviceName broadcast`
    local setIpCommand=""

    if [ -n "$ip" ]; then
        setIpCommand="${setIpCommand} $deviceName $ip "
    else
        echo -e "::$LINENO) \e[1;33;41m (Err)::  Nic $nicName ip is empty. \033[0m"
        return
    fi
    if [ -n "$broadcast" ]; then
        setIpCommand="${setIpCommand}  broadcast $broadcast "
    fi
    if [ -n "$netmask" ]; then
        setIpCommand="${setIpCommand}  netmask $netmask "
    fi
    if [ -n "$setIpCommand" ]; then
        setIpCommand="ifconfig ${setIpCommand}"
        if [ $debug == true ]; then
            echo -e "::$LINENO)\033[33m  setIpCommand = $setIpCommand \033[0m"
        fi
        exec $setIpCommand | true
    fi
}

function daemonIpAddress()
{
    ProcNumber=`ps -ef |grep "SetNetworkInfo"|grep -v "grep"|wc -l`
    if [ $ProcNumber -ne 1 ]; then
        if [ $debug == true ]; then
            echo -e "::$LINENO)\033[33m  The daemon thread has started \033[0m"
        fi
        exit 0
    fi
    createPath $dataPath
    isInitial=false
    # The thread starts to monitor IP changes
    while :
    do
        sleep 5
        for nicName in ${NIC_NameArray[*]}
        do
            local autoNicFileFlag=${isAutoFlagPath_Prefix}${nicName}
            # Check whether the NIC to be enumerated is automatically obtained
            if test -e $autoNicFileFlag
            then
                if [ $debug == true ]; then
                    echo -e "::$LINENO)\033[33m  The current status is automatically obtaining IP addresses of NIC[$nicName] \033[0m"
                fi
                if [ $isInitial == false ]; then
                    autoObtainIpForSpecifiedNicName $nicName
                fi
            else
                # There is no NIC name that automatically obtains the IP tag file
                if test -e $cacheFilePath
                then
                    local cacheIp=`readCacheConfig $cacheFilePath $nicName ip`
                    if [ -n "$cacheIp" ]; then
                        if [ $debug == true ]; then
                            echo -e "::$LINENO)\033[33m The current status is reading static IP addresses from the configuration file of NIC[$nicName] \033[0m"
                        fi
                        # If the NIC has been configured with an IP address
                        local netIp=`ifconfig $nicName | grep "inet addr:" | ${awkPath} '{print $2}' | cut -c 6-`
                        if [ $cacheIp != $netIp ]; then
                            if [ $debug == true ]; then
                                echo -e "::$LINENO)\033[33m  The cache IP address[$cacheIp] of NIC $nicName" \
                                "is different from the network IP address[$netIp], and will be reset \033[0m"
                            fi
                            setIpconfigByNicName "[$nicName]"
                        fi
                        setDefaultRoute
                    else
                        # If no IP address is configured for the NIC, use the default IP address
                        setToDefaultStaticIpForSpecifiedNicName ${nicName}
                    fi
                else
                    setToDefaultStaticIpForSpecifiedNicName ${nicName}
                fi
            fi
        done
        isInitial=true
    done
}

function startupDaemonIpAddress()
{
    if [ $debug == true ]; then
        echo "::$LINENO) The network card ip daemon will be started."
    fi
    daemonIpAddress
}

function createPath()
{
    path="$1"
    if [ ! -d "$path" ]; then
        mkdir -p $path | true
    fi
}

function createParentsPath()
{
    cachePath="$(dirname "$1")"
    createPath $cachePath
}

function createFiles()
{
    createParentsPath $cacheFilePath
    if test -e $cacheFilePath
    then
        if [ $debug == true ]; then
            echo "::$LINENO) $cacheFilePath already exists"
        fi
    else
        if [ $debug == true ]; then
            echo -e "::$LINENO)\033[33m  Cache file::$cacheFilePath does not exist,will be created \033[0m"
        fi
        touch $cacheFilePath
    fi
}

function cacheNetworkInfo()
{
    nicElementVar=($1)
    deviceName=$(echo ${nicElementVar[4]} | ${awkPath} -F '=' '{print $2}')
    # Gets whether the NIC is cached
    if [ `grep -c "\[${deviceName}\]" $cacheFilePath` -ne "0" ];then
        keyRow=$(sed -n '/'"\[${deviceName}\]"'/=' $cacheFilePath)
        if [ $debug == true ]; then
            echo "::$LINENO) The name of an existing device[${deviceName}] is in line ::($keyRow) of the $cacheFilePath file"
        fi
        # Write gateway and ip information
        for item in ${nicElementVar[@]}
        do
            key=$(echo ${item} | ${awkPath} -F '=' '{print $1}')
            value=$(echo ${item} | ${awkPath} -F '=' '{print $2}')
            if [ "$key" != "device" ]
            then
                if [ -n "$value" ]; then
                    local keySelector=$(cat $cacheFilePath|${awkPath} '/'"\[${deviceName}\]"'/{f=1;next} /\[*\]/{f=0} f'| ${awkPath} '/'"$key"'/' )
                    local sectionLineSelector=$(sed -n -e "/\[${deviceName}\]/=" $cacheFilePath)
                    if [ -n "$keySelector" ]; then
                        if [ $debug == true ]; then
                            echo "::$LINENO)  ${deviceName} on the line $sectionLineSelector,[$keySelector] will be changed to[${value}]"
                        fi
                        sed -i "${sectionLineSelector},/^\[.*\]/s/\($key.\?=\).*/\1${value}/g" $cacheFilePath >/dev/null 2>&1
                    else
                        if [ $debug == true ]; then
                            echo -e "::$LINENO)\033[33m  key \"$key\" does not exist in section,$key=${value},will be inserted \033[0m"
                        fi
                        sed -i "${sectionLineSelector}a ${key}=${value}" $cacheFilePath
                    fi
                fi
            else
                :
            fi
        done
    else
        writeNicWhenItemNotExists "${nicElementVar[*]}"
    fi
    removeAutoFlagForSpecifiedNicName $deviceName
    daemonIpAddress
}

function writeNicWhenItemNotExists()
{
    nicElementVar=($1)
    # If the NIC cache information does not exist, write the first line; otherwise, write the last line
    fileRows=$(sed -n '$=' $cacheFilePath)
    if [ ! -n "$fileRows" ]; then
        if [ $debug == true ]; then
            echo "::$LINENO) $cacheFilePath is empty"
        fi
        deviceName=$(echo ${nicElementVar[4]} | ${awkPath} -F '=' '{print $2}')
        echo "[${deviceName}]" > $cacheFilePath
    else
        # Add the cache configuration information in the last line
        sed -i '$a '"[${deviceName}]"'' $cacheFilePath
    fi
    # Write gateway and ip information
    for item in ${nicElementVar[@]}
    do
        key=$(echo ${item} | ${awkPath} -F '=' '{print $1}')
        value=$(echo ${item} | ${awkPath} -F '=' '{print $2}')
        if [ "$key" != "device" ]
        then
            if [ -n "$value" ]; then
                echo "$key=${value}" >> $cacheFilePath
            fi
        else
            :
        fi
    done
}

# Automatically obtains an IP address assigned by DHCP
function autoObtainsByDHCP()
{
    local prefix=$2
    createParentsPath $prefix
    # Delete all autotag files each time. If the corresponding NIC name is passed, 
    local rmCommand="rm -rf ${prefix}*"
    exec $rmCommand | true
    # set the specified NIC name to automatically obtain
    local deviceName=$(echo ${netWorkConfig[4]} | ${awkPath} -F '=' '{print $2}')
    local devCount=$(echo "$deviceName" | ${awkPath} '{n=split($0, array, ",")} END{print n }')

    if [ -n "$deviceName" ]; then
        for i in $(seq 1 $devCount)
        do
            local nicElement=$(echo "$deviceName" | ${awkPath} '{n=split($0, array, ",")} END{print array['"$i"'] }')
            local nicAutoFileFlag="${prefix}${nicElement}"
            touch $nicAutoFileFlag
            #TODO Delete specified section
            autoObtainIpForSpecifiedNicName ${nicElement}
        done
    else
        for nicElement in ${NIC_NameArray[@]}
        do
            local nicAutoFileFlag="${prefix}${nicElement}"
            touch $nicAutoFileFlag
        done
        if test -e $1
        then
            #Delete cache static files and generate automatic fetch tags
            rm -rf $1 | true
        fi
    fi
    daemonIpAddress
}